<template>
  <div class="xtx-city">
    <div class="select" @click.stop="showFn">
      <span class="placeholder" v-if="!changeResult.provinceName" >请选择配送地址</span>
      <span class="value">{{changeResult.provinceName}}{{changeResult.cityName}}{{changeResult.countyName}}</span>
      <i class="iconfont icon-angle-down"></i>
    </div>
    <div class="option" v-if="show">
      <span class="ellipsis" @click.stop="optionClick(i)" v-for="i in toList" :key="i">{{i.name}}</span>
    </div>
  </div>
</template>
<script>
import { ref, reactive } from 'vue'
import axios from 'axios'
export default {
  name: 'XtxCity',
  emits: ['chenge'],
  setup (pors, { emit }) {
    const toList = ref([])
    const show = ref(false)
    const changeResult = reactive({
      provinceCode: '', // 省code
      provinceName: '', // 省名称
      cityCode: '', // 城市code
      cityName: '', // 城市名称
      countyCode: '', // 地区code
      countyName: '' // 地区名
    })
    function showFn () {
      for (const key in changeResult) {
        changeResult[key] = ''
      }
      if (!show.value) {
        axios.get('https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json')
          .then((res) => {
            toList.value = res.data
          })
      }
      show.value = !show.value
    }
    function optionClick (obj) {
      toList.value = obj.areaList
      if (obj.level === 0) {
        changeResult.provinceCode = obj.code
        changeResult.provinceName = obj.name
      }
      if (obj.level === 1) {
        changeResult.cityCode = obj.code
        changeResult.cityName = obj.name
      }
      if (obj.level === 2) {
        changeResult.countyCode = obj.code
        changeResult.countyName = obj.name
        show.value = false
      }
      emit('chenge', changeResult)
    }
    document.addEventListener('click', () => {
      show.value = false
    })
    return {
      toList,
      showFn,
      show,
      changeResult,
      optionClick
    }
  }
}
</script>
<style scoped lang="less">
.xtx-city {
  display: inline-block;
  position: relative;
  z-index: 400;
  margin-left: 10px;
  .select {
    border: 1px solid #e4e4e4;
    height: 30px;
    padding: 0 5px;
    line-height: 28px;
    cursor: pointer;
    &.active {
      background: #fff;
    }
    .placeholder {
      color: #999;
    }
    .value {
      color: #666;
      font-size: 12px;
    }
    i {
      font-size: 12px;
      margin-left: 5px;
    }
  }
  .option {
    width: 542px;
    border: 1px solid #e4e4e4;
    position: absolute;
    left: 0;
    top: 29px;
    background: #fff;
    min-height: 30px;
    line-height: 30px;
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    > span {
      width: 130px;
      text-align: center;
      cursor: pointer;
      border-radius: 4px;
      padding: 0 3px;
      &:hover {
        background: #f5f5f5;
      }
    }
  }
}
</style>
